from flask import Blueprint
from flask import g, jsonify, request

from app.api import handle_error, verify_params
from app.util.jwt import verify_jwt, generate_jwt, auth_check
from app.common.result import falseReturn, trueReturn
from app.models.Auth import Auth
from app.models.Student import Student

auth_blueprint = Blueprint('auth_blueprint', __name__, url_prefix='/auth')


@auth_blueprint.before_request
@handle_error
def before_request():
    if request.get_data():
        g.data = request.get_json(silent=True)
    else:
        g.data = {}
    Authorization = request.headers.get('Authorization', None)
    auth_check(Authorization)


@auth_blueprint.route('/signin', methods=['POST'])
@handle_error
@verify_params(params=['auth_id', 'password'])
def sign_in():
    auth_id = g.data.get('auth_id', None)
    password = g.data.get('password', None)
    result = Auth.verify_password(auth_id=auth_id, password=password)
    if result:
        token = generate_jwt(auth_id)
        return trueReturn(data={"token": token}, msg='登录成功')
    else:
        return falseReturn(msg='登录失败')


@auth_blueprint.route('', methods=['POST'])
@handle_error
@verify_params(params=['auth_id', 'password', 'priority'])
def new_auth():
    auth_id = g.data.get('auth_id', None)
    password = g.data.get('password', None)
    priority = g.data.get('priority', None)
    auth = Auth.insert_account(auth_id=auth_id, password=password, priority=priority)
    if auth is None:
        return falseReturn(msg='id重复，请检查')
    else:
        return trueReturn(msg='创建成功')


@auth_blueprint.route('/validToken', methods=['POST'])
@handle_error
def test():
    if g.auth_id is not None:
        if g.priority == 0:
            user = Student.get_by_studentId(g.auth_id)
            msg = 'student'
        else:
            user = g.auth_id
            msg = 'admin'
        return trueReturn(data={"user": user}, msg=msg)
    else:
        return falseReturn(msg='失败')
